from com.wws.sw4sy.common import win32, imageDeal, ocr
from com.wws.sw4sy.tasks.commonOperations import *
import time, re


# sw4sy = win32.get_sw4sy_win_hd()

# 师门具体任务按钮（完成任务后自动弹出那个）
def click_shimen_button():
    win32.click(sw4sy, 1261,432)


# 送我回去
def click_back_to_shimen_button():
    win32.click(sw4sy, 1261,436)


# 点击右边任务栏的师门任务字体，启动师门任务
def click_right_task_list_shimen_text():
    win32.click(sw4sy, 1171, 219)


# 点击我要做任务
def click_i_want_to_do_task():
    win32.click(sw4sy, 1260,436)


# 必须通用
def flow_shi_men():
    # one_turn(True)
    #print("第一轮完成")
    # one_turn()
    one_turn_new()
    print("********师门任务完成*********")


# 一轮师门
def one_turn(need_check_left_right=False):
    initTaskType = None
    if need_check_left_right:
        if not is_open_left_task_list():
            # 打开左边任务栏
            open_left_task_list()
        time.sleep(1)
        # 先看右边任务栏是否有师门任务，有就避免使用点日程-师门的方式开启任务（人物在购买物品时，很近商店会遮挡住右边任务栏师门两个字）
        if not is_open_right_task_list():
            print("打开右边任务栏")
            open_right_task_list()

    # TODO 如果不是在任务tab，有问题
    # click_right_task_list_renwu_button()
    # 看右边任务栏
    imagebytes = imageDeal.screenshot(1149, 192, 1382, 609, workPath + "resources/tmp/right_task_list.png")
    word = ocr.toText(imagebytes, "师")
    if word is None:
        print("使用点日程-师门的方式开启任务")
        click_task_button()
        time.sleep(1)
        click_task_shimen_button()

        # 有时候太快交完了任务，就出现师门具体任务按钮了
        imagebytes = imageDeal.screenshot(958, 409, 1322, 453, workPath + "resources/tmp/do_task_button.png")
        word = ocr.toText(imagebytes, "师")
        if word is not None:
            # 开始当前任务
            click_shimen_button()
            print("----点击开始师门任务按钮----")
        else:
            time.sleep(6)
            # 是否需要点击 ‘我要做任务’
            imagebytes = imageDeal.screenshot(931, 410, 1322, 458, workPath + "resources/tmp/i_want_to_do_task.png")
            word = ocr.toText(imagebytes, "我要做任务")
            if word is not None:
                print(f"点击我要做任务:word:{word}")
                click_i_want_to_do_task()
            else:
                print(f"不需要点击我要做任务:word:{word}")


    else:
        print("从右边栏启动任务：")
        initTaskType = word[3:7]
        pattern = re.compile(r'\d+')  # 查找数字
        result1 = pattern.findall(word)
        tmpstr = result1[0]
        if tmpstr.isdigit():
            initTimes = int(tmpstr)
        else:
            # 识别结果中没有数字
            print("警告，识别不到任务环数，默认为第1环")
            initTimes = 1

        click_right_task_list_shimen_text()
        print("点击右边任务栏的师门任务字体，启动师门任务")
        time.sleep(1)

    # 次数
    times = 0
    while times < 10:
        print("--------------start-----------------")
        need_wait_time_to_reach_shifu = True
        times += 1

        # 判断任务类型，执行相关操作
        taskType = None
        # 类型重新归类
        taskTypeBelong = None
        if initTaskType is not None:
            taskType = initTaskType
            # 修正环数
            times = initTimes
            initTaskType = None
            initTimes = -1
        else:
            imagebytes = imageDeal.screenshot(958, 409, 1322, 453, workPath + "resources/tmp/do_task_button.png")
            word = ocr.toText(imagebytes, "师")
            time.sleep(1)
            if word is not None:
                if word.find("今天已完成20环", 0, len(word)) > 0:
                    print("今天已完成20环")
                    break
                # 开始当前任务
                click_shimen_button()
                print("点击开始师门任务按钮")
            else:
                print("不用点击开始师门任务按钮")
                if not is_open_right_task_list():
                    print("打开右边任务栏")
                    open_right_task_list()

                time.sleep(1)
                # 按钮没出来，就看右边任务栏
                imagebytes = imageDeal.screenshot(1149, 192, 1382, 609, workPath + "resources/tmp/right_task_list.png")
                word = ocr.toText(imagebytes, "师")

            taskType = word[3:7]
            pattern = re.compile(r'\d+')  # 查找数字
            result1 = pattern.findall(word)
            tmpstr = result1[0]
            if tmpstr.isdigit():
                times = int(tmpstr)
            else:
                # 识别结果中没有数字
                print("警告，识别不到任务环数，不修正环数")

        # TODO 识别有问题时，比如环数识别到大于10，会导致误判完成
        print(f"当前任务类型:{taskType},当前环数:{times}，等待13秒进行重归类...")
        time.sleep(11)

        #TODO 改为循环效率会更高，得到需要的操作就推出循环
        # 这个，可能是很近师父，身上已经有给予的物品了。需要给予检测
        if deal_geiyu_1():
            time.sleep(6)
            continue

        # 打架（判断左边出现日程）
        if is_in_war():
            taskTypeBelong = "打架"
        # 买东西（判断在逛摊界面（需要判断给予），宠物店，药品店，武器店，饰品店）
        elif check_is_tanweiliebiao_page():
            taskTypeBelong = "购买摊位商品"
        elif check_is_chongwudian_page():
            taskTypeBelong = "宠物交易"
        elif check_is_fushidian_page():
            taskTypeBelong = "买服饰"
        elif check_is_wuqidian_page():
            taskTypeBelong = "买武器"
        elif check_is_yaodian_page():
            taskTypeBelong = "买药品"
        # 拜访（很快重新出现做师门按钮）
        else:
            taskTypeBelong = "拜访"

        print(f"当前任务类型:{taskType},当前环数:{times},重新归类为：{taskTypeBelong}")

        if taskTypeBelong == "打架":
            while is_in_war():
                time.sleep(5)
        elif taskTypeBelong == "购买摊位商品":
            do_tanwei_buy()
            # 等待到达师父
            time.sleep(4)
            # 处理 “给予”问题
            deal_geiyu_1()
            need_wait_time_to_reach_shifu = False
        elif taskTypeBelong == "宠物交易":
            click_s_chongwu_buy_button()
            time.sleep(6)
            # 等待到达师父
            # 处理身上刚好有宠物的情况
            # TODO (身上最好不要带宝宝）只带一个宠物就行
            need_wait_time_to_reach_shifu = False
        elif taskTypeBelong == "买服饰":
            click_s_fushidian_buy_button()
        elif taskTypeBelong == "买武器":
            click_s_wuqidian_buy_button()
        elif taskTypeBelong == "买药品":
            click_s_yaodian_buy_button()
        # 拜访（很快重新出现做师门按钮）
        else:
            # "拜访"
            None

        # 等待自动交任务完成(到达师父）
        if need_wait_time_to_reach_shifu is True:
            time.sleep(6)
        # 检测拖动验证，并处理
        # 391, 290，942,604
        if check_need_validate():
            print("需要拖动验证")
            time.sleep(10)
        print("--------------end-----------------")


# 判断是否是师门具体任务与按钮（识别不可靠啊！！！TODO）
def check_is_to_do_shimen_button():
    try:
        x, y = imageDeal.mathc_img(931,407, 1347,484, workPath + "resources/img/shimen_todo_button.png")
        if x != -1 and y != -1:
            return True
        return False
    except:
        return False


# 判断是否是师门 我要做任务按钮
def check_is_i_want_to_do_shimen_button():
    try:
        x, y = imageDeal.mathc_img(961,412, 1095,450, workPath + "resources/img/i_want_to_do_shimen.png")
        if x != -1 and y != -1:
            return True
        return False
    except:
        return False


# 判断是否是 送我回去 按钮
def check_is_back_to_shimen_button():
    try:
        x, y = imageDeal.mathc_img(963,414, 1072,449, workPath + "resources/img/shimen_back_to.png")
        if x != -1 and y != -1:
            return True
        return False
    except:
        return False

# 判断是否是 今天已完成20环 按钮
def check_is_end_shimen_button():
    try:
        x, y = imageDeal.mathc_img(1173,412, 1245,446, workPath + "resources/img/shimen_wancheng_20_pic.png")
        if x != -1 and y != -1:
            return True
        return False
    except:
        return False


def one_turn_new():
    print("使用点日程-师门的方式开启任务")
    click_task_button()
    time.sleep(1)
    click_task_shimen_button()
    time.sleep(4)
    if check_is_end_shimen_button():
        print("完成20环师门")
        return
    #我要做任务
    # if check_is_i_want_to_do_shimen_button():
    #     click_i_want_to_do_task()
    # time.sleep(13)

    # 次数
    times = 0
    # 判断任务类型，执行相关操作
    taskType = None
    need_wait_time_to_reach_shifu = True
    excptionTimes = 0
    while times < 20:
        print(f"--------------start-----{times+1}------------")

        if deal_geiyu_1_use_img():
            print("发现给予")
        else:
            print("未发现给予")

        # 检测是否已完成20环
        if check_is_end_shimen_button():
            print("完成20环师门")
            break
        else:
            print("未发现完成20环")
        if check_is_back_to_shimen_button():
            click_back_to_shimen_button()
            #等待到达师父
            time.sleep(6)
        else:
            print("未发现送我回去")
        # 我要做任务
        if check_is_i_want_to_do_shimen_button():
            click_i_want_to_do_task()
        else:
            print("未发现我要做任务")
        if check_is_to_do_shimen_button():
            excptionTimes = 0
            print("发现师门按钮，点击")
            click_shimen_button()
            # 启动了，走路
        else:
            excptionTimes += 1
            print(f"未发现师门按钮,次数：{excptionTimes}")

        # time.sleep(13)

        t = 0
        af = False
        while True:
            # 打架（判断左边出现日程）
            if is_in_war():
                taskType = "打架"
            # 买东西（判断在逛摊界面（需要判断给予），宠物店，药品店，武器店，饰品店）
            elif check_is_tanweiliebiao_page():
                taskType = "购买摊位商品"
            elif check_is_chongwudian_page():
                taskType = "宠物交易"
            elif check_is_fushidian_page():
                taskType = "买服饰"
            elif check_is_wuqidian_page():
                taskType = "买武器"
            elif check_is_yaodian_page():
                taskType = "买药品"
            # 拜访（很快重新出现做师门按钮）
            else:
                taskType = "拜访"
                print(taskType)
                # 这个，可能是很近师父，身上已经有给予的物品了。需要给予检测
                if check_is_to_do_shimen_button():
                    excptionTimes = 0
                    print("拜访中，发现师门按钮，点击")
                    click_shimen_button()
                    # 启动了，走路
                    t=0

                elif deal_geiyu_1_use_img():
                    print("拜访中，发现给予，退出内部循环")
                    t=0
                    break
                elif check_is_back_to_shimen_button():
                    print("拜访中，发现送我回去，退出内部循环")
                    click_back_to_shimen_button()
                    # 等待到达师父
                    t = 0
                    break

                time.sleep(2)

            if taskType != "拜访":
                times += 1
                break
            else:
                t +=1

            if t > 6:
                af = True
                print("t=6,退出内部循环")
                break

        if af :
            print("从新启动一次师门，走路中...")
            click_task_button()
            time.sleep(1)
            click_task_shimen_button()
            time.sleep(6)
            continue

        print(f"当前任务类型:{taskType},当前环数:{times}")

        # 拜访（很快重新出现做师门按钮）
        if taskType == "拜访":
            None
        elif taskType == "打架":
            while is_in_war():
                time.sleep(3)
        elif taskType == "购买摊位商品":
            do_tanwei_buy()
            # 等待到达师父
            time.sleep(4)
            # 处理 “给予”问题
            deal_geiyu_1()
            need_wait_time_to_reach_shifu = False
        elif taskType == "宠物交易":
            click_s_chongwu_buy_button()
            time.sleep(6)
            # 等待到达师父
            # 处理身上刚好有宠物的情况
            # TODO (身上最好不要带宝宝）只带一个宠物就行
            need_wait_time_to_reach_shifu = False
        elif taskType == "买服饰":
            click_s_fushidian_buy_button()
        elif taskType == "买武器":
            click_s_wuqidian_buy_button()
        elif taskType == "买药品":
            click_s_yaodian_buy_button()
        else:
            print("-------??-----")
            None

        # 等待自动交任务完成(到达师父）
        if need_wait_time_to_reach_shifu is True:
            time.sleep(6)
        # 检测拖动验证，并处理
        # 391, 290，942,604
        if check_need_validate():
            print("需要拖动验证")
            time.sleep(10)
        print(f"--------------end--------{times}---------")



if __name__ == '__main__':
    win32.set_window_active(sw4sy)
    flow_shi_men()
    # count = 0
    # for i in range(0,1000):
    #     if not check_is_end_shimen_button():
    #         count += 1
    # print(f"识别失败次数：{count}")

    exit()
